﻿using EYangFramework.Common.BasicHelper;
using EYangFramework.Common.Ninject;
using EYangFramework.Common.Timer;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static EYangFramework.Common.BasicHelper.SerializeHelper;

namespace EYangFrame.DataAccess.Global
{
    //此类用于自动定时将缓存界面的数据读出来并写入数据库
    public class WriteTempToDbAuto
    {
        public WriteTempToDbAuto()
        {
            TimerProvider.SingtonTimer.Event += ReadTempToDb;
        }
        private void ReadTempToDb(object sender, EventArgs args)
        {
            DbContext Context = NinjectProvider.NinjectCore.GetService<DbContext>();
            try
            {
                Context.Database.Connection.Open();

                SerializeHelper serializeHelper = new SerializeHelper();
                List<TempObject> tempObjects = serializeHelper.DeserializeFromTemp();
                if (tempObjects.Count <= 0)
                {
                    return;
                }
                EYangDbContext eYangDb = Context as EYangDbContext;
                using (DbContextTransaction transaction = Context.Database.BeginTransaction())
                {
                    foreach (var to in tempObjects)
                    {
                        Type type = Type.GetType(to.DataType);
                        DbSet set = Context.Set(type);
                        object entity = serializeHelper.DeserializeFromJson(to.Instance, type);
                        if (!set.Local.Contains(entity))
                        {
                            set.Attach(entity);
                        }
                        switch (to.EntityState)
                        {
                            case 0:
                                Context.Entry(entity).State = EntityState.Added;
                                break;
                            case 1:
                                Context.Entry(entity).State = EntityState.Modified;
                                break;
                            case 2:
                                Context.Entry(entity).State = EntityState.Deleted;
                                break;
                        }
                    }
                    Context.SaveChanges();
                    transaction.Commit();
                }
            }
            catch (Exception)
            { }
            finally
            {
                Context.Database.Connection.Close();
            }
        }
    }
}
